package cn.com.zpark.dbcp;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @PackageName: cn.com.zpark.dbcp
 * @ClassName: DBCPUtils02
 * @Description:
 * @author: RZS
 * @date: 2021/10/31  16:46
 */
public class DBCPUtils02 {

    // 定义数据源
    private static DataSource dataSource;

    /**
     * 初始化资源
     */
    static {
        // 创建properties集合工具类
        Properties properties = new Properties();
        // 获取配置文件流对象
        InputStream stream = DBCPUtils02.class.getClassLoader().getResourceAsStream("dbcp.properties");
        // 加载配置文件
        try {
            properties.load(stream);

            // 创建数据源
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            System.out.println("资源加载失败");
            e.printStackTrace();
        }

    }

    /**
     * 获取连接对象
     */
    public static Connection getConn() throws Exception {
        return dataSource.getConnection();
    }

    /**
     * 关闭连接
     */
    public static void close(ResultSet res, Connection conn, Statement... stat){
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        /**************可变参数*************/

        for (Statement statement : stat) {
            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        /**************可变参数*************/


        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
